import React, { useContext, useState, useEffect, useImperativeHandle, useMemo } from 'react';
import { ApplyUpdateContext } from '../common/ApplyContext';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import { DescriptionsType, useDescriptionsType } from '@/components/DescriptionsType';
import {
  getUserDepName,
  getUserName,
  getUserDepID,
  getUserID,
  getPersonalInfo,
  getInvoiceCode,
  getPosName,
  getDeptPosTreeIcon,
  getCompanyID,
  getUserDeptFlag,
} from '@/utils';
import { KYFW_Type, KYWZ_Type, PURCHASE_Type, supplyWayList, ZNGL_Type } from '../common/Format';
import { ApplyUpdateAPI } from '../common/type';
import { Form, TreeSelect } from 'antd';
import moment from 'moment';
import { getCompanyTreeNodeListSev, getFlowOrgTreeByOrgIDService } from '@/services/BaseLayout';
import { findValueFun, renderFileFunc } from '@/common';
import { UploadFormCommon } from '@/components/UploadForm';

/**
 * @UpdateStepsBaseInfo 步骤条一基本信息
 * @returns
 */
const UpdateStepsBaseInfo = React.forwardRef(({}: ApplyUpdateAPI.IUpdateStepsBaseInfoProps, ref) => {
  /**解构上下文*/
  const { prefixCls, applyInfo, dispatch, locationProps, finallyType } = useContext(ApplyUpdateContext);
  /**表单实例*/
  const [formRef] = Form.useForm();

  /**是否展示对象*/
  const [isShowObj, setIsShowObj] = useState<Record<string, any>>({
    isShowUpload: 0, // 标的来源
    isShowOther: 0, // 其他
    isShowCommon: 0, // 是否共性
    isShowPlatform: 0, // 是否平台
    isShowCategory: getUserDeptFlag() == 0 ? 2 : 0, // 采购类别
    isShowConsign: 0, // 是否会签
    isShowMeeting: 0, // 是否会议
  });
  // /**标的来源*/
  // const [isShowUpload, setIsShowUpload] = useState<number>(0);
  // /**是否显示其他*/
  // const [isShowOther, setIsShowOther] = useState<number>(0);

  const [companyListState, setCompanyListState] = useState<Record<string, any>[]>([]);

  /**获取业务部门数据*/
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();

  /**获取最大部门数据*/
  const { companyTreeNodeListRun, companyTreeNodeListLoading, companyTreeNodeList } = getCompanyTreeNodeListSev();

  /**处理数据去掉岗位*/
  const handleNotPostion = (treeData: Record<string, any>[]) => {
    const loopTree = (dataList: Record<string, any>[]) => {
      dataList?.forEach((item: any, index: number) => {
        if (item?.textType == '0' || item?.textType == '1') {
          const childrenList: Record<string, any>[] = item?.children?.filter((itemChil: any) => itemChil?.textType == '0' || itemChil?.textType == '1');
          dataList[index] = {
            ...item,
            title: (
              <span>
                {finallyType == 'view' ? '' : getDeptPosTreeIcon(String(item?.textType))}
                {item?.text}
              </span>
            ),
            children: childrenList?.length > 0 ? loopTree(childrenList) : null,
            disabled: item?.textType == '0' ? true : false,
            // disabled: item?.dutyPositionID ? false : true
          };
        }
      });
      return dataList;
    };

    const treeList: Record<string, any>[] = loopTree(treeData);
    return treeList;
  };

  // const companyListMemo = useMemo(() => {
  //   return handleNotPostion(companyTreeNodeList)
  // }, [isShowObj])

  useEffect(() => {
    if (companyTreeNodeList?.length) {
      setCompanyListState(handleNotPostion(companyTreeNodeList));
    } else {
      setCompanyListState([]);
    }
  }, [companyTreeNodeList]);

  /**表格表单配置信息*/
  const [config, { setFieldsValue, validateFields }] = useDescriptionsType({
    labelWidth: 240,
    basicForm: formRef,
    isShowNumTitle: false,
    schemas: [
      {
        key: 'applyInfoDes',
        title: '基本信息',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'applyTime',
            component: 'Input',
            placeholder: '自动带出',
            // initialValue: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
            initialValue: moment(new Date()).format('YYYY-MM-DD'),
            disabled: true,
            required: false,
          },
          {
            label: '流水单号',
            field: 'applyCode',
            component: 'Input',
            disabled: true,
            initialValue: getInvoiceCode('SQ'),
            placeholder: '自动带出',
          },
          {
            label: '申请人',
            field: 'applyerName',
            placeholder: '自动带出',
            component: 'Input',
            disabled: finallyType == 'view',
          },
          {
            label: '联系方式',
            field: 'contactMobile',
            component: 'Input',
            disabled: finallyType == 'view',
            placeholder: '自动带出',
          },
          {
            label: '申请部门/单位',
            field: 'applyDepartmentName',
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            label: '职务岗位',
            field: 'applyPositionName',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            label: '采购项目名称',
            field: 'applyTitle',
            component: 'Input',
            disabled: finallyType == 'view',
            required: true,
            placeholder: '请输入',
            colSpan: 2,
          },

          // {
          //   label: '资金来源',
          //   field: 'projectName',
          //   component: 'Input',
          //   required: true,
          //   disabled: true,
          //   placeholder: '请选择',
          //   contentAfter:
          //     finallyType == 'view' ? null : (
          //       <a>
          //         <SearchOutlined
          //           onClick={() => {
          //             onChangeSelectProjectState(true);
          //           }}
          //         />
          //       </a>
          //     ),
          // },
          // {
          //   label: '资金来源编号',
          //   field: 'projectCode',
          //   component: 'Input',
          //   placeholder: '自动带出',
          //   disabled: true,
          // },
          {
            label: '采购类别',
            field: 'purchCategory',
            component: 'Render',
            disabled: finallyType == 'view',
            colSpan: 1,
            render: (text = 0, record) => {
              if (finallyType == 'view') {
                return <span>{findValueFun(PURCHASE_Type, text)}</span>;
              } else {
                return (
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'purchCategory'}
                    defalultKeys={getUserDeptFlag() == 1 ? 0 : getUserDeptFlag() == 0 ? 2 : 0}
                    onChange={(val) => setIsShowObj({ ...isShowObj, isShowCategory: val })}
                    radioList={
                      getUserDeptFlag() == 1
                        ? PURCHASE_Type?.filter((item) => item.value != 2)
                        : getUserDeptFlag() == 0
                        ? PURCHASE_Type?.filter((item) => item.value == 2)
                        : PURCHASE_Type
                    }
                    radioDisabled={finallyType == 'view'}
                  />
                );
              }
            },
          },
          {
            label: '采购内容',
            field: 'purchContent',
            component: 'Render',
            disabled: finallyType == 'view',
            colSpan: 1,
            render: (text = 0, record) => {
              if (finallyType == 'view') {
                return (
                  <span>
                    {record?.purchCategory == 0
                      ? findValueFun(KYWZ_Type, text)
                      : record?.purchCategory == 1
                      ? findValueFun(KYFW_Type, text)
                      : record?.purchCategory == 2
                      ? findValueFun(ZNGL_Type, text)
                      : '--'}
                  </span>
                );
              } else {
                return (
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'purchContent'}
                    defalultKeys={Number(text)}
                    onChange={(val) => setIsShowObj({ ...isShowObj, isShowOther: val })}
                    radioList={
                      record?.purchCategory == 0 ? KYWZ_Type : record?.purchCategory == 1 ? KYFW_Type : record?.purchCategory == 2 ? ZNGL_Type : KYWZ_Type
                    } //ZNGL_Type
                    radioDisabled={finallyType == 'view'}
                  />
                );
              }
            },
          },
          {
            label: '其他内容',
            field: 'otherContent',
            component: 'InputTextArea',
            disabled: finallyType == 'view',
            colSpan: 2,
            ishidden: isShowObj?.isShowOther == 3 ? false : true,
            placeholder: finallyType == 'view' ? '--' : '请选择',
            required: true,
            showCount: true,
            allowClear: true,
            maxLength: 200,
            autoSize: { minRows: 4, maxRows: 6 },
          },
          {
            label: '是否共性',
            field: 'commonFlag',
            component: 'Render',
            colSpan: isShowObj?.isShowCommon == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowCategory == 1 || isShowObj?.isShowCategory == 2 ? true : false,
            slotRender: (text: any = 0) => {
              if (finallyType == 'view') {
                return <span style={{ marginLeft: '8px' }}>{text == 0 ? '否' : text == 1 ? '是' : '--'}</span>;
              }
              return (
                <div style={{ marginLeft: '8px' }}>
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'commonFlag'}
                    defalultKeys={text}
                    formRequired={true}
                    onChange={(val) => setIsShowObj({ ...isShowObj, isShowCommon: val })}
                    radioList={[
                      {
                        value: 0,
                        name: '否',
                      },
                      {
                        value: 1,
                        name: '是',
                      },
                    ]}
                  />
                </div>
              );
            },
          },
          {
            label: '实验室业务归口部门',
            field: 'commonDepartmentID',
            component: 'TreeSelect',
            placeholder: finallyType == 'view' ? '--' : '请选择',
            colSpan: isShowObj?.isShowCommon == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowCommon == 0 ? true : isShowObj?.isShowCategory == 1 || isShowObj?.isShowCategory == 2 ? true : false,
            messageTrue: '请选择实验室业务归口部门',
            required: true,
            disabled: finallyType == 'view' || applyInfo?.checkState ? true : false,
            showArrow: finallyType == 'view' || applyInfo?.checkState ? false : true,
            treeData: companyListState,
            fieldNames: {
              label: 'title',
              value: 'id',
              children: 'children',
            } as Record<string, any>,
            showSearch: true,
            treeNodeFilterProp: 'text',
            allowClear: true,
          },
          {
            label: '是否平台',
            field: 'platformFlag',
            component: 'Render',
            colSpan: isShowObj?.isShowPlatform == 0 ? 2 : 1,
            slotRender: (text: any = 0) => {
              if (finallyType == 'view') {
                return <span style={{ marginLeft: '8px' }}>{text == 0 ? '否' : text == 1 ? '是' : '--'}</span>;
              }
              return (
                <div style={{ marginLeft: '8px' }}>
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'platformFlag'}
                    defalultKeys={text}
                    formRequired={true}
                    onChange={(val) => setIsShowObj({ ...isShowObj, isShowPlatform: val })}
                    radioList={[
                      {
                        value: 0,
                        name: '否',
                      },
                      {
                        value: 1,
                        name: '是',
                      },
                    ]}
                  />
                </div>
              );
            },
          },
          {
            label: '平台归口部门',
            field: 'platformDepartmentID',
            component: 'TreeSelect',
            placeholder: finallyType == 'view' ? '--' : '请选择',
            messageTrue: '请选择平台归口部门',
            required: true,
            colSpan: isShowObj?.isShowPlatform == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowPlatform == 0 ? true : false,
            disabled: finallyType == 'view' || applyInfo?.checkState ? true : false,
            showArrow: finallyType == 'view' || applyInfo?.checkState ? false : true,
            treeData: companyListState,
            fieldNames: {
              label: 'title',
              value: 'id',
              children: 'children',
            } as Record<string, any>,
            showSearch: true,
            treeNodeFilterProp: 'text',
            allowClear: true,
          },
          {
            label: '是否会签',
            field: 'consignFlag',
            component: 'Render',
            colSpan: isShowObj?.isShowConsign == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowCategory == 0 || isShowObj?.isShowCategory == 1 ? true : false,
            slotRender: (text: any = 0) => {
              if (finallyType == 'view') {
                return <span style={{ marginLeft: '8px' }}>{text == 0 ? '否' : text == 1 ? '是' : '--'}</span>;
              }
              return (
                <div style={{ marginLeft: '8px' }}>
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'consignFlag'}
                    defalultKeys={text}
                    formRequired={true}
                    onChange={(val) => setIsShowObj({ ...isShowObj, isShowConsign: val })}
                    radioList={[
                      {
                        value: 0,
                        name: '否',
                      },
                      {
                        value: 1,
                        name: '是',
                      },
                    ]}
                  />
                </div>
              );
            },
          },
          {
            label: '实验室会签部门',
            field: 'consignDepartmentID',
            component: 'TreeSelect',
            placeholder: finallyType == 'view' ? '--' : '请选择',
            messageTrue: '请选择实验室会签部门',
            required: true,
            colSpan: isShowObj?.isShowConsign == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowConsign == 0 ? true : isShowObj?.isShowCategory == 0 || isShowObj?.isShowCategory == 1 ? true : false,
            disabled: finallyType == 'view' || applyInfo?.checkState ? true : false,
            showArrow: finallyType == 'view' || applyInfo?.checkState ? false : true,
            treeData: companyListState,
            fieldNames: {
              label: 'title',
              value: 'id',
              children: 'children',
            } as Record<string, any>,
            showSearch: true,
            treeNodeFilterProp: 'text',
            allowClear: true,
          },
          {
            label: '是否上会',
            field: 'meetingFlag',
            component: 'Render',
            colSpan: isShowObj?.isShowMeeting == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowCategory == 0 || isShowObj?.isShowCategory == 1 ? true : false,
            slotRender: (text: any = 0) => {
              if (finallyType == 'view') {
                return <span style={{ marginLeft: '8px' }}>{text == 0 ? '否' : text == 1 ? '是' : '--'}</span>;
              }
              return (
                <div style={{ marginLeft: '8px' }}>
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'meetingFlag'}
                    defalultKeys={text}
                    formRequired={true}
                    onChange={(val) => setIsShowObj({ ...isShowObj, isShowMeeting: val })}
                    radioList={[
                      {
                        value: 0,
                        name: '否',
                      },
                      {
                        value: 1,
                        name: '是',
                      },
                    ]}
                  />
                </div>
              );
            },
          },
          {
            label: '会议纪要',
            field: 'meetingSummaryUrl',
            placeholder: '请上传会议纪要',
            component: 'Render',
            colSpan: isShowObj?.isShowMeeting == 0 ? 2 : 1,
            ishidden: isShowObj?.isShowMeeting == 0 ? true : isShowObj?.isShowCategory == 0 || isShowObj?.isShowCategory == 1 ? true : false,
            required: true,
            slotRender: (text, record) => {
              if (finallyType == 'view') {
                return (
                  <span style={{ marginLeft: 8 }}>
                    {renderFileFunc({
                      record: applyInfo,
                      fileName: 'meetingSummaryUrl',
                      downloadAddress: '/purchaseApplyController/downloadFile',
                      returnStr: '/',
                    })}
                  </span>
                );
              }
              return (
                <div>
                  <UploadFormCommon
                    form={formRef}
                    fileFormName={'meetingSummaryUrl'}
                    spanCol={24}
                    inRowProportion={24}
                    name={'attachFile'}
                    required={true}
                    url={'/purchaseApplyController/uploadFile'}
                    downloadUrl={'/purchaseApplyController/downloadFile'}
                    fileFormDelName={'delFile'}
                    defaultFiles={text}
                    maxFile={1}
                    hintTitle={'只能上传 1 个！'}
                    fieldBusiPath={'purchase/apply'}
                    delFunc={(delFilePath) => {}}
                  >
                    上传
                  </UploadFormCommon>
                </div>
              );
            },
          },
          {
            label: '标的来源',
            field: 'supplyWay',
            component: 'Render',
            disabled: finallyType == 'view' || (applyInfo?.id && applyInfo?.mpurchasePacks != null),
            placeholder: '请选择',
            colSpan: 2,
            render: (text = 0) => {
              if (finallyType == 'view' || (applyInfo?.id && applyInfo?.mpurchasePacks != null)) {
                let word: any = <span style={{ color: '#bfc0c1' }}>自动匹配</span>;
                if (typeof text != 'undefined') {
                  word = <span>{findValueFun(supplyWayList, text)}</span>;
                }
                return word;
              }
              return (
                <TagSelect
                  colSpan={24}
                  formLabel={''}
                  formName={'supplyWay'}
                  defalultKeys={text}
                  onChange={(val) => setIsShowObj({ ...isShowObj, isShowUpload: val })}
                  radioList={supplyWayList}
                  radioDisabled={finallyType == 'view'}
                />
              );
            },
          },
          {
            label: '采购理由',
            field: 'applyInfo',
            component: 'InputTextArea',
            placeholder: '请输入',
            required: true,
            showCount: true,
            allowClear: true,
            maxLength: 200,
            autoSize: { minRows: 4, maxRows: 6 },
            disabled: finallyType == 'view',
            colSpan: 2,
          },
        ],
      },
    ],
  });

  /**暴露给父组件的实例值 */
  useImperativeHandle(ref, () => ({ validateFields }));

  useEffect(() => {
    /**获取组织机构信息*/
    getFlowOrgTreeRun({ params: 0, flowType: 'null' });
    companyTreeNodeListRun();
    /**页面类型*/
    let { type } = locationProps;

    if (type === 'add') {
      // 初始新增表单
      setFieldsValue({
        contactMobile: getPersonalInfo()?.phoneMobile,
        applyDepartmentName: getUserDepName(),
        applyPositionName: getPosName(),
        applyerName: getUserName(),
      });
      // setIsShowObj({
      //   isShowUpload: 0, // 标的来源
      //   isShowOther: 0, // 是否展示其他
      //   isShowCommon: 0, // 共性
      //   isShowPlatform: 0, // 平台
      //   isShowCategory: getUserDeptFlag() == 0 ? 2 : 0, // 采购类别
      //   isShowConsign: 0, // 是否会签
      // })
    } else if (type === 'edit' || type === 'view') {
      // 回填表单
      if (applyInfo?.id) {
        setFieldsValue({
          ...applyInfo,
          applyTime: moment(applyInfo?.applyTime).format('YYYY-MM-DD'),
          supplyWay: Number(applyInfo?.supplyWay),
          platformFlag: Number(applyInfo?.platformFlag),
          commonFlag: Number(applyInfo?.commonFlag),
          consignFlag: Number(applyInfo?.consignFlag),
        });
        setIsShowObj({
          isShowUpload: applyInfo?.supplyWay || 0, // 标的来源
          isShowOther: applyInfo?.purchContent || 0, // 是否展示其他
          isShowCommon: applyInfo?.commonFlag || 0, // 共性
          isShowPlatform: applyInfo?.platformFlag || 0, // 平台
          isShowCategory: applyInfo?.purchCategory || 0, // 采购类别
          isShowConsign: applyInfo?.consignFlag || 0, // 会签
          isShowMeeting: applyInfo?.meetingFlag || 0, // 上会
        });
      }
    }
  }, [locationProps, applyInfo]);

  return (
    <div className={`${prefixCls}-steps-baseInfo`}>
      <DescriptionsType config={config} />
    </div>
  );
});

export default UpdateStepsBaseInfo;

/**选择项目弹窗组件渲染状态*/
// const [isShowSelectProject, setIsShowSelectProject] = useState<boolean>(false);

{
  /* 资金来源--弹窗 */
}
{
  /* {isShowSelectProject && (
        <UpdateProjectModal
          onSave={(param: Record<string, any>) => onChangeSelectProjectState(true, param)}
          onClose={() => onChangeSelectProjectState(false)}
        />
      )} */
}

// const onChangeSelectProjectState = (state: boolean, param: Record<string, any> = {}) => {
//   setIsShowSelectProject(state);
//   if (Object.keys(param).length) {
//     /** 给表单赋值 */
//     setFieldsValue({ projectName: param.projectName, projectCode: param.projectCode });
//     /** 给reducer */
//     dispatch({ type: IContractsActionEnum.UpdataProJect, payload: param });
//   }
// };
